%
%
%  Intensity calculation for Imaris
%
%
%  Installation:
%
%  - Copy this file into the XTensions folder in the Imaris installation directory
%  - You will find this function in the Image Processing menu
%
%    <CustomTools>
%      <Menu>
%       <Submenu name="McGill">
%        <Item name="Intensity Calculation" icon="Matlab" tooltip="Use this to calculate intensities in Oocyte and Nurse cells">
%          <Command>Matlab::MGIntensity(%i)</Command>
%        </Item>
%       </Submenu>
%      </Menu>
%      <SurpassTab>
%        <SurpassComponent name="bpSurfaces">
%           <Item name="Intensity Calculation" icon="Matlab" tooltip="Use this to calculate intensities in Oocyte and Nurse cells">
%               <Command>Matlab::MGIntensity(%i)</Command>
%           </Item>
%        </SurpassComponent>
%      </SurpassTab>
%    </CustomTools>
%  
%
%  Description:
%
%   Uses two surfaces to calculate intensities in oocyte and nurse cells
%   Author: Hendrik Golzke, Patrik Rath
%   Last change: 2010-09-24
function MGIntensity(aImarisApplicationID, optionalBoolAutomated)
    sVersionString = '100924';
    
    function aiXYReturn = SearchStage(cellData)
        %Search for 'Stage:' in cell array
        if (strcmp(cellData{10,1},'Stage:'))
            aiXYReturn = [10,1];
            return
        end;
        for iRow=1:size(cellData,1)
            for iCol=1:size(cellData,2)
                if (strcmp(cellData{iRow,iCol},'Stage:'))
                    aiXYReturn = [iRow, iCol];
                    return
                end;
            end;
        end;
    end

    function aiXYReturn = SearchComment(cellData)
        %Search for 'Stage:' in cell array
        if (strcmp(cellData{11,1},'Stage:'))
            aiXYReturn = [11,1];
            return
        end;
        for iRow=1:size(cellData,1)
            for iCol=1:size(cellData,2)
                if (strcmp(cellData{iRow,iCol},'Comment:'))
                    aiXYReturn = [iRow, iCol];
                    return
                end;
            end;
        end;
        %Some old files have no comment place present
        aiXYReturn = [11,1];
    end
    
    %Maybe we run this script automated?
    if (~exist('optionalBoolAutomated','var'))
        bAuto = false;
    else
        bAuto = optionalBoolAutomated;
    end;

    % connect to Imaris Com interface
    if ~isa(aImarisApplicationID, 'COM.Imaris_Application')
      vImarisServer = actxserver('ImarisServer.Server');
      if ischar(aImarisApplicationID)
        aImarisApplicationID = round(str2double(aImarisApplicationID));
      end
      apImaris = vImarisServer.GetObject(aImarisApplicationID);
    else
      apImaris = aImarisApplicationID;
    end
    

    %Set undo point if we are in manual mode
    if (~bAuto)
        apImaris.DataSetPushUndo('Intensity calculation');
    end;
    
    %Load Data (Channels), always work on a clone. This way Imaris doesn't
    %update the display which is enormously slow ...
    dsChannels = apImaris.mDataSet.Clone;
    
    %Get data like dimensions &c.
    iDimChannels = dsChannels.mSizeC;
    %If we see old masked channels present we just delete them
    if (    strcmp(dsChannels.GetChannelName(iDimChannels-1),'masked oocyte in GFP') && ...
            strcmp(dsChannels.GetChannelName(iDimChannels-2),'masked nurse cells in GFP') && ...
            strcmp(dsChannels.GetChannelName(iDimChannels-3),'Nurse cells and oocyte in GFP') && ...
            strcmp(dsChannels.GetChannelName(iDimChannels-4),'Oocyte in mCherry') && ...
            strcmp(dsChannels.GetChannelName(iDimChannels-5),'Nursecell in mCherry') && ...
            strcmp(dsChannels.GetChannelName(iDimChannels-6),'Anti oocyte in mCherry') && ...
            strcmp(dsChannels.GetChannelName(iDimChannels-7),'Anti nurse cells and oocyte in mCherry') )
        dsChannels.Resize(0,dsChannels.mSizeX,0,dsChannels.mSizeY,0,dsChannels.mSizeZ,0,dsChannels.mSizeC-7,0,dsChannels.mSizeT);
        iDimChannels = dsChannels.mSizeC;
    end
    
    
    for iChannel=0:iDimChannels-1
        apImaris.SetChannelVisibility(iChannel,false);
    end;

    %Search channels for AF569 (makes Structures visible)
    bBreak = false;
    for iChannel = 0:(iDimChannels-1)
        if (~isequal([],strfind(dsChannels.GetChannelName(iChannel),'AF568')) || ~isequal([],strfind(dsChannels.GetChannelName(iChannel),'mCherry'))|| ~isequal([],strfind(dsChannels.GetChannelName(iChannel),'mcherry')))
            bBreak = true;
            break;
        end;
    end;

    if (~bBreak)
        error('Found no channel named AF568 or mCherry');
    end;
    iStructureChannel = iChannel;

    %Search channels for GFP (the protein we are interested in)
    bBreak = false;
    for iChannel = 0:(iDimChannels-1)
        if (~isequal([],strfind(dsChannels.GetChannelName(iChannel),'GFP')))
            bBreak = true;
            break;
        end;
    end;

    if (~bBreak)
        error('Found no channel named GFP');
    end;
    iDataChannel = iChannel;

    %%
    %Open Objects and find surfaces
    vSurpassScene = apImaris.mSurpassScene;
    iChildren = vSurpassScene.GetNumberOfChildren;
    aSurfaces = [];
    for iChild = 0:(iChildren-1)
        %The IsSurface function is sometimes buggy, so alternatively seek
        %surfaces by name
        bIsSurface=false;
        try
            bIsSurface = apImaris.mFactory.IsSurfaces(vSurpassScene.GetChild(iChild));
        catch
            %It seems we have to save first to access the surfaces at all
            try
                bIsSurface = ~isequal([],regexp(vSurpassScene.GetChild(iChild).mName,'^Surfaces \d+$'));
            catch
                error('Please save first and/or restart Imaris, otherwise this script won''t be able to access the surfaces. Remember to use the "Save as ..." button as the other is buggy. (Maybe we should write some more bug reports :-P ...)');
            end;
        end;
        if (bIsSurface)
            aSurfaces = [ aSurfaces, vSurpassScene.GetChild(iChild)];
        end;
        %Setting the volume to invisible might increase performance,
        %especially when loading a file with lots of channels since Imaris
        %7.1.1 doesn't save channel visibility.
        if (apImaris.mFactory.IsVolume(vSurpassScene.GetChild(iChild)))
            vSurpassScene.GetChild(iChild).mVisible=false;
        end;
    end;

    %Check and let user choose surfaces
    if (length(aSurfaces) > 2)
        %if we are automated send error
        if (bAuto)
            error(['There are more than two surfaces present in file ' apImaris.GetCurrentFileName]);
        end;
        %Else let user chose one
        aTempSurfaces = [];
        for iSurface = 1:length(aSurfaces)
            sChoice = questdlg(strcat('Shall we use surface ''',aSurfaces(iSurface).mName,''' for calculations?'),'Surface selection','Use','Don''t Use','Use');
            if (strcmp('Use',sChoice))
                aTempSurfaces = [aTempSurfaces, aSurfaces(iSurface)];
            end;
            if (length(aTempSurfaces)==2)
                break;
            end;
        end;
        aSurfaces=aTempSurfaces;
    end;


    if (length(aSurfaces) < 2)
        error('You need at least two volumes for this operation.' );
    end;


    %Get masks out of surfaces
    %This GetMask is really strange, first two 3-tuples choose volume (given in
    %percent) last 3-tuple gives resolution
    aMasks = [aSurfaces(1).GetMask(dsChannels.mExtendMinX,dsChannels.mExtendMinY,dsChannels.mExtendMinZ, ...
        dsChannels.mExtendMaxX,dsChannels.mExtendMaxY,dsChannels.mExtendMaxZ,...
        dsChannels.mSizeX,dsChannels.mSizeY,dsChannels.mSizeZ,0),...
        aSurfaces(2).GetMask(dsChannels.mExtendMinX,dsChannels.mExtendMinY,dsChannels.mExtendMinZ, ...
        dsChannels.mExtendMaxX,dsChannels.mExtendMaxY,dsChannels.mExtendMaxZ,...
        dsChannels.mSizeX,dsChannels.mSizeY,dsChannels.mSizeZ,0)];

    %Initialize Intensity and Pixels
    iIntensity=zeros(1,3);
    iPixels=zeros(1,3);

    %Go through our whole stack
    for iZCoordinate = 0:(dsChannels.mSizeZ-1)
        iPixels(1)=iPixels(1)+sum(sum(aMasks(1).GetDataSlice(iZCoordinate,0,0)));
        iPixels(2)=iPixels(2)+sum(sum(aMasks(2).GetDataSlice(iZCoordinate,0,0)));
        iPixels(3)=iPixels(3)+sum(sum( aMasks(1).GetDataSlice(iZCoordinate,0,0) | aMasks(2).GetDataSlice(iZCoordinate,0,0) ));
        %Multiply mask with data and sum it up (automatically typecasting does
        %not work -> convert to double manually
        iIntensity(1)=iIntensity(1) + sum(sum( double(dsChannels.GetDataSlice(iZCoordinate, iDataChannel, 0)) .* double(aMasks(1).GetDataSlice(iZCoordinate,0,0)) ));
        iIntensity(2)=iIntensity(2) + sum(sum( double(dsChannels.GetDataSlice(iZCoordinate, iDataChannel, 0)) .* double(aMasks(2).GetDataSlice(iZCoordinate,0,0)) ));
        iIntensity(3)=iIntensity(3) + sum(sum( double(dsChannels.GetDataSlice(iZCoordinate, iDataChannel, 0)) .* double( aMasks(1).GetDataSlice(iZCoordinate,0,0)| aMasks(2).GetDataSlice(iZCoordinate,0,0) ) ));
    end;


    %Calculate volume in um^3
    dVolume = iPixels * (dsChannels.mExtendMaxX-dsChannels.mExtendMinX)/dsChannels.mSizeX * ...
        (dsChannels.mExtendMaxY-dsChannels.mExtendMinY)/dsChannels.mSizeY * ...
        (dsChannels.mExtendMaxZ-dsChannels.mExtendMinZ)/dsChannels.mSizeZ;

    %Calculate mean intensities
    %The larger part is going to be nursecells
    iSmaller=2;
    if (iPixels(1)<iPixels(2))
        iSmaller=1;
    end;
    dMeanIntensityOocyte = iIntensity(iSmaller)/dVolume(iSmaller);
    %The nursecells are the union of all pixels - oocyte
    dMeanIntensityNurseCells = (iIntensity(3)-iIntensity(iSmaller))/(dVolume(3)-dVolume(iSmaller));

    %Make seven new channels for the applied masks
    dsChannels.Resize(0,dsChannels.mSizeX,0,dsChannels.mSizeY,0,dsChannels.mSizeZ,0,dsChannels.mSizeC+7,0,dsChannels.mSizeT)

    %Go through our whole stack, this has to be done after determining
    %which channel is oocyte and nursecells
    iSizeOfOocyte = 0;
    iSliceBigOoc = 0;
    aiStartOfBin=1:100:25000;
    aiHitsNur=zeros(length(aiStartOfBin),1);
    aiHitsOoc=zeros(length(aiStartOfBin),1);
    for iZCoordinate = 0:(dsChannels.mSizeZ-1)
        %Create mask of Oocyte and nursecells
        aiMaskNurseOoc = uint16(aMasks(1).GetDataSlice(iZCoordinate,0,0)|aMasks(2).GetDataSlice(iZCoordinate,0,0));
        aiMaskOoc = uint16(aMasks(iSmaller).GetDataSlice(iZCoordinate,0,0) );
        %Anti nursecells and oocyte in structure channel
        aiPic = uint16(~(aiMaskNurseOoc)) .* uint16(dsChannels.GetDataSlice(iZCoordinate,iStructureChannel,0));
        dsChannels.SetDataSlice( aiPic, iZCoordinate,dsChannels.mSizeC-7);
        %Anti oocyte in structure channel
        aiPic = uint16(~(aMasks(iSmaller).GetDataSlice(iZCoordinate,0,0))) .* uint16(dsChannels.GetDataSlice(iZCoordinate,iStructureChannel,0));
        dsChannels.SetDataSlice( aiPic, iZCoordinate,dsChannels.mSizeC-6);
        %Nursecells in original data
        aiPic = uint16( aiMaskNurseOoc - aiMaskOoc ) .* uint16(dsChannels.GetDataSlice(iZCoordinate,iStructureChannel,0));
        dsChannels.SetDataSlice( aiPic, iZCoordinate,dsChannels.mSizeC-5);
        %Oocyte in original data
        aiPic = uint16(aMasks(iSmaller).GetDataSlice(iZCoordinate,0,0)) .* uint16(dsChannels.GetDataSlice(iZCoordinate,iStructureChannel,0));
        dsChannels.SetDataSlice( aiPic, iZCoordinate,dsChannels.mSizeC-4);
        %Calculate and write nursecells+oocyte GFP into channel
        aiPic = uint16(dsChannels.GetDataSlice(iZCoordinate,iDataChannel, 0)) .* aiMaskNurseOoc;
        dsChannels.SetDataSlice( aiPic, iZCoordinate,dsChannels.mSizeC-3,0);
        %Calculate and write masked nursecells GFP into channel
        aiPic = uint16(dsChannels.GetDataSlice(iZCoordinate,iDataChannel, 0)) .* uint16(  aiMaskNurseOoc - uint16(aMasks(iSmaller).GetDataSlice(iZCoordinate,0,0)) );
        dsChannels.SetDataSlice( aiPic , iZCoordinate,dsChannels.mSizeC-2,0);
        %Do histogram
        [aiTempHist]=hist(aiPic,aiStartOfBin);
        aiHitsNur=aiHitsNur + sum(aiTempHist,2);
        %Calculate and write masked Oocyte GFP into channel
        aiPic = uint16(dsChannels.GetDataSlice(iZCoordinate, iDataChannel, 0)) .* uint16(  aMasks(iSmaller).GetDataSlice(iZCoordinate,0,0));
        dsChannels.SetDataSlice( aiPic , iZCoordinate,dsChannels.mSizeC-1,0);
        %Do histogram
        [aiTempHist]=hist(aiPic,aiStartOfBin);
        aiHitsOoc=aiHitsOoc + sum(aiTempHist,2);
        %Determine slide where oocyte is the biggest for output
        if (iSizeOfOocyte<sum(sum(aiMaskOoc)))
            iSizeOfOocyte  = sum(sum(aiMaskOoc));
            iSliceBigOoc = iZCoordinate;
        end;
    end;
    
    %Normalize histograms
    aiHitsNur = aiHitsNur /(iPixels(3)-iPixels(iSmaller));
    aiHitsOoc = aiHitsOoc /iPixels(iSmaller);
    
    %Fit gaussian peak (throw away last and first bin before)
    aiStartOfBin = aiStartOfBin(2:end-1)';
    aiHitsOoc = aiHitsOoc(2:end-1);
    aiHitsNur = aiHitsNur(2:end-1);
%     adFit=polyfit(aiStartOfBin, log(aiHitsNur),2);
%     dSigmaNur=sqrt(-0.5/adFit(1));
%     dMuNur=adFit(2)*dSigmaNur^2;
%     adFit=polyfit(aiStartOfBin, log(aiHitsOoc),2);
%     dSigmaOoc=sqrt(-0.5/adFit(1));
%     dMuOoc=adFit(2)*dSigmaOoc^2;

    %Set name &c.
    dsChannels.SetChannelName( dsChannels.mSizeC-7,'Anti nurse cells and oocyte in mCherry');
    dsChannels.SetChannelName( dsChannels.mSizeC-6,'Anti oocyte in mCherry');
    dsChannels.SetChannelName( dsChannels.mSizeC-5,'Nursecell in mCherry');
    dsChannels.SetChannelName( dsChannels.mSizeC-4,'Oocyte in mCherry');
    dsChannels.SetChannelName( dsChannels.mSizeC-3,'Nurse cells and oocyte in GFP');
    dsChannels.SetChannelName( dsChannels.mSizeC-2,'masked nurse cells in GFP');
    dsChannels.SetChannelName( dsChannels.mSizeC-1,'masked oocyte in GFP');
    dsChannels.SetChannelColor(dsChannels.mSizeC-1,1,0,1,0);

    %Set colour range to full range
    for iChannel= dsChannels.mSizeC-8:dsChannels.mSizeC-1
        dsChannels.SetChannelRange(iChannel,0,65023);
    end;

    %Set copied dataset as default one
    apImaris.mDataSet = dsChannels;

    %Set visibility of channels
    for iChannel=0:dsChannels.mSizeC-1
        apImaris.SetChannelVisibility(iChannel,false);
    end;
    apImaris.SetChannelVisibility(dsChannels.mSizeC-3,true);
      
    
    %Write to file (but before get current name and give it another ending)
    sFilename=apImaris.GetCurrentFileName;
    sOriginalFilePath=sFilename;
    Sourcefile=sFilename;
    sFilename = [sFilename(1:end-4) '_' sVersionString '.xls'];

    %Let user choose where to save data if we are not automated
    if (~bAuto)
        [sFilename,sDir]=uiputfile('.xls','Select where to save data and enter file name',sFilename);
    else
        %Cut sFilename into dir and file by backslashes
        aiBackslashes = regexp(sFilename,'\\');
        if (isempty(aiBackslashes))
            error(['Filename corrupted for file ' sFilename]);
        end;
        sDir = sFilename(1:aiBackslashes(end));
        sFilename = sFilename(aiBackslashes(end)+1:end);
    end;
    if ( (~isequal(sFilename,0)) && (~isequal(sDir,0)) )
        %try to locate any old files and extract data from them
        sOtherFiles = regexprep(sFilename,'\d{6}','*');
        lOlderVersions = dir([sDir sOtherFiles]);
        if ~isempty(lOlderVersions)
            [~,~,cellData] = xlsread([sDir '\' lOlderVersions(end).name],'Data');
            aiCoord = SearchComment(cellData)+[0,1];
            cellComment= cellData(aiCoord(1,1),aiCoord(1,2));
            aiCoord = SearchStage(cellData)+[0,1];
            cellStage  = cellData(aiCoord(1,1),aiCoord(1,2));
        else
            cellComment = {''};
            cellStage   = {'unknown'};
        end;
        
        M={'','avInt (per um^3)','avInt (per Voxel)', 'num_pix', 'Int','Volume'};
        M(2,1)=cellstr('Oocyte');
        M(3,1)=cellstr('Nursecells');
        M(4,1)=cellstr('Ratio of Intensities (oocyte/nursecells)');
        M(2,2)=num2cell(dMeanIntensityOocyte);
        M(3,2)=num2cell(dMeanIntensityNurseCells);
        M(4,2)=num2cell(dMeanIntensityOocyte/dMeanIntensityNurseCells);
        M(2,3)=num2cell(iIntensity(iSmaller)/iPixels(iSmaller));
        M(3,3)=num2cell((iIntensity(3)-iIntensity(iSmaller))/(iPixels(3)-iPixels(iSmaller)));
        M(2,4)=num2cell(iPixels(iSmaller));
        M(3,4)=num2cell(iPixels(3)-iPixels(iSmaller));
        M(2,5)=num2cell(iIntensity(iSmaller));
        M(3,5)=num2cell(iIntensity(3)-iIntensity(iSmaller));
        M(2,6)=num2cell(dVolume(iSmaller));
        M(3,6)=num2cell(dVolume(3)-dVolume(iSmaller));
        
        M(4,3)=cellstr('Average intensity of oocyte compared to overall average intensity');
        M(4,4)=num2cell( dMeanIntensityOocyte/(iIntensity(3)/dVolume(3)) );

        M(5,3)=num2cell(iPixels(iSmaller)/(iPixels(3)-iPixels(iSmaller)));
        M(5,2)={'relative volume(Oocyte/Eggchamber):'};

        M(6,1)={'SourceFiles:'};
        M(6,2)=cellstr(Sourcefile);
        
        M(7,1)=cellstr('Size of Voxels');
        M(7,2)=cellstr('x');
        M(7,3)=cellstr('y');
        M(7,4)=cellstr('z');
        M(8,1)=cellstr(['in ' dsChannels.mUnit]);
        M(8,2)=num2cell((dsChannels.mExtendMaxX-dsChannels.mExtendMinX)/dsChannels.mSizeX);
        M(8,3)=num2cell((dsChannels.mExtendMaxY-dsChannels.mExtendMinY)/dsChannels.mSizeY);
        M(8,4)=num2cell((dsChannels.mExtendMaxZ-dsChannels.mExtendMinZ)/dsChannels.mSizeZ);
        M(10,1)=cellstr('Stage:');
        M(10,2)=cellStage;
        M(11,1)=cellstr('Comment:');
        M(11,2)=cellComment;
        M(12,1)=cellstr(['Version: ' sVersionString]);
        
        M21={'Start of bin','Oocyte','Nurse cells'};
        M22=num2cell([aiStartOfBin,aiHitsOoc,aiHitsNur]);

        try
            if (exist([sDir sFilename],'file'))
                %Turn off warnings for delete file
                warning('off','MATLAB:DELETE:Permission');
                %Turn on recycling of files, just in case ...
                sRecycle = recycle('on');
                delete([sDir sFilename]);
                recycle(sRecycle);
                if (exist([sDir sFilename],'file'))
                    error(['Couldn''t delete file ' sDir sFilename]);
                end;
            end;
            warning off MATLAB:xlswrite:AddSheet;
            xlswrite([sDir sFilename],M22,'Histogram','A2');
            xlswrite([sDir sFilename],M21,'Histogram','A1');
            xlswrite([sDir sFilename],M,'Data');
        catch    
            error(['Can''t write into file "' sDir sFilename '". Is the file opened by Excel?']);
        end;
            
        %Also write the biggest oocyte slide as a thumbnail for quick views
        if (exist([sDir sFilename(1:end-3) 'thumb.tif'],'file'))
            %Automatically yes, if in manual mode, ask
            if (bAuto)
                sOverwrite = 'Yes';
            else
                sOverwrite=questdlg(['Trying to create tif file as a preview. File ' sDir sFilename ' already exists.' char(10) 'Shall the file be overwritten?'],'File already exists');
            end;
            %Delete file if set to yes
            if (strcmp('Yes',sOverwrite))
                delete([sDir sFilename(1:end-3) 'thumb.tif']);
            end;
        else
            sOverwrite='Yes';
        end;
        if (strcmp('Yes',sOverwrite))
            aiPic = dsChannels.GetDataSlice(iSliceBigOoc,dsChannels.mSizeC-4, 0)+dsChannels.GetDataSlice(iSliceBigOoc,dsChannels.mSizeC-5, 0);
            %Transpose aiPic, because rows and cols are mixed up
            imwrite(aiPic', [sDir sFilename(1:end-3) 'thumb.tif'], 'compression','none');
        end;
        
        %Also write the channels as tif files
        sChannelDir = [sDir sFilename(1:end-3) 'Channels'];
        %check whether dir is existing, if so delete it after asking
        if (exist(sChannelDir,'file'))
            %Don't ask in auto mode
            if (bAuto)
                sOverwrite = 'Yes';
            else
                sOverwrite=questdlg(['The directory' sChannelDir ' already exists.' char(10) 'Shall the directory be deleted in order to save the channels as tif-files?'],'Directory already exists');
            end;
            if (strcmp('Yes',sOverwrite))
                try
                    rmdir(sChannelDir,'s');
                    mkdir(sDir,[sFilename(1:end-3) 'Channels']);
                catch
                    error(['Can''t delete directory ' sChannelDir char(10) 'Maybe some programme is still accessing it?']);
                end;
            end;
        end;
        
        %Overwrite Imaris file if auto-mode is on this is because it
        %takes ages to load such a file
        if (bAuto)
            sOverwrite = 'Yes';
        else
            sOverwrite = questdlg(['Shall we save the changes to the Imaris file right now?' char(10) sOriginalFilePath],'Save file');
        end;
        if strcmp('Yes', sOverwrite)
            try
                apImaris.FileSave(sOriginalFilePath,'writer="Imaris5"');
            catch
                error(['Imaris error: Can''t write into file ' sOriginalFilePath]);
            end;
        end;
        
        %save tiff
        apImaris.FileSave([sChannelDir '\' sFilename(1:end-3)],'writer="OmeTiff"');
        %go into dir and name files according to channels
        lList=dir(sChannelDir);
        for iFile=3:length(lList)
            %Move files according to channel names
            sSearchString = sprintf('_C%02d.',iFile-3);
            sNewName=regexprep(lList(iFile).name,sSearchString,[sSearchString dsChannels.GetChannelName(iFile-3) '.']);
            if (strcmp(sNewName,lList(iFile).name))
                sSearchString = sprintf('_C%d.',iFile-3);
                sNewName=regexprep(lList(iFile).name,sSearchString,[sSearchString dsChannels.GetChannelName(iFile-3) '.']);
            end;
            %Matlab's movefile is too slow since it copies the files!
            system(['rename "' sChannelDir '\' lList(iFile).name '" "' sNewName '"']);
        end;
        
        %If we are not in auto mode open the original file again
        if (~bAuto && strcmp(sOverwrite,'Yes') )
            apImaris.FileOpen(sOriginalFilePath);
        end;
    end;
end